package com.nwpu.intimacy.user;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.utils.CacheUtil;

public class ModifyInformationActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/modify";

	private SharedPreferences sp_userMessage;

	private EditText modify_information_edit;
	private Button modify_ok_button;
	private Button modify_cancel_button;

	private String modifyInformation;

	private final static int USER_MODIFY_SUCCESS = 0x114;
	private final static int USER_MODIFY_FAIL = 0x115;

	private Handler modifyHandler;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_modifyinformation);

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		initLayout();

		modify_cancel_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(),
						UserInformationActivity.class);

				startActivity(intent);

				finish();

			}
		});

		modify_ok_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (modify_information_edit.getText().toString().equals("")) {

					Toast.makeText(getApplicationContext(), "请填写修改信息!",
							Toast.LENGTH_SHORT).show();

					return;

				}

				modifyInformation = modify_information_edit.getText()
						.toString();

				if (onCheck(modifyInformation)) {

					Toast.makeText(getApplicationContext(), "输入信息过长，请重新输入!",
							Toast.LENGTH_SHORT).show();

					return;

				}

				onModify();

			}
		});

		// 线程交互
		modifyHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_MODIFY_SUCCESS: {

					Toast.makeText(getApplicationContext(), "修改成功!",
							Toast.LENGTH_SHORT).show();

					Intent intent = new Intent();
					intent.setClass(getApplicationContext(),
							UserInformationActivity.class);

					startActivity(intent);

					finish();

					break;
				}
				case USER_MODIFY_FAIL: {

					Toast.makeText(getApplicationContext(), "修改错误!",
							Toast.LENGTH_SHORT).show();

				}
				default:
					super.handleMessage(msg);
				}
			}

		};
	}

	public boolean onCheck(String modify) {

		if (modify.length() > 50) {

			return true;

		}

		return false;

	}

	// 初始化控件
	public void initLayout() {

		modify_information_edit = (EditText) findViewById(R.id.modify_information_edit);
		modify_ok_button = (Button) findViewById(R.id.modify_ok_button);
		modify_cancel_button = (Button) findViewById(R.id.modify_cancel_button);

	}

	// 判断用户修改信息类型，并向服务器发送请求
	public void onModify() {

		new Thread() {

			public void run() {

				try {

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					Bitmap photo = CacheUtil.GetFromFile(
							sp_userMessage.getString("USER_NAME", ""), "Photo");

					jsonObject.put("username",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("password",
							sp_userMessage.getString("PASSWORD", ""));
					jsonObject.put("portrait", bitmaptoString(photo));

					jsonObject.put("sex", sp_userMessage.getInt("SEX", 0));
					jsonObject.put("comment", modifyInformation);
					jsonObject
							.put("area", sp_userMessage.getString("AREA", ""));

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("modify",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					Log.e("result", result);
					Log.e("hkq", URLDecoder.decode(result, HTTP.UTF_8));
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("result").equals("success")) {

						sp_userMessage.edit()
								.putString("COMMENT", modifyInformation)
								.commit();
						Message msg = new Message();
						msg.what = USER_MODIFY_SUCCESS;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_MODIFY_FAIL;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	/**
	 * 将Bitmap格式图片转化为字符串
	 * 
	 * @param bitmap
	 * @return
	 */
	public String bitmaptoString(Bitmap bitmap) {

		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}
}
